package leetcode.offer_two_special.array;

import java.util.HashMap;

/**
 * @author mazouri
 * @create 2021-09-05 17:26
 */
public class _11_findMaxLength {
    public int findMaxLength(int[] nums) {
        int maxLen = 0;
        int preSum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        //-1是为了处理一开始就减0的情况
        map.put(0, -1);

        for (int i = 0; i < nums.length; i++) {
            preSum += nums[i] == 0 ? -1 : 1;
            if (map.containsKey(preSum)) {
                maxLen = Math.max(maxLen, i - map.get(preSum));
            } else {
                map.put(preSum, i);
            }
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(new _11_findMaxLength().findMaxLength(new int[]{0, 1, 0}));
    }
}
